package com.softlab.retailwholesalesystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.softlab.retailwholesalesystem.entity.AuthorityEntity;
import com.softlab.retailwholesalesystem.entity.MenuEntity;
import com.softlab.retailwholesalesystem.service.IAuthorityService;
import com.softlab.retailwholesalesystem.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/authority")
public class AuthorityController extends BaseController{

    @Autowired
    IAuthorityService service;

    @GetMapping("/add")
    public JsonResult<Void> addAuthority(AuthorityEntity authority){
        service.save(authority);
        return new JsonResult<>(200,"增加权限成功");
    }

    @GetMapping
    public JsonResult<List<AuthorityEntity>> getAllAuthority(){
        AuthorityEntity authority = new AuthorityEntity();
        authority.setIsDelete(0);
        List<AuthorityEntity> list = service.getList(authority);
        return new JsonResult<>(200,"获取成功",list);
    }

    @GetMapping("/search")
    public JsonResult<List<AuthorityEntity>> searchAuthority(AuthorityEntity authority){
        List<AuthorityEntity> list = service.getList(authority);
        return new JsonResult<>(200,"获取成功",list);
    }

    @GetMapping("/delete")
    public JsonResult<Void> deleteAuthority(AuthorityEntity authority){
        QueryWrapper<AuthorityEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id",authority.getRoleId())
                .eq("menu_id",authority.getMenuId())
                .eq("is_delete",0);
        List<AuthorityEntity> list = service.list(wrapper);
        for (AuthorityEntity one : list) {
            if (one!=null){
                authority.setAuthorityId(one.getAuthorityId());
                authority.setIsDelete(1);
                service.updateById(authority);
                return new JsonResult<>(200,"删除成功");
            }
        }
        return new JsonResult<>(500,"该权限不存在");
    }

    @GetMapping("{id}")
    public JsonResult<List<MenuEntity>> getRoleAuthorities(@PathVariable int id){
        List<MenuEntity> list = service.getRoleAuthorities(id);
        return new JsonResult<>(200,"获取权限成功",list);
    }

}
